#!/bin/sh
# Created 2010-05-27 by Jimmy Wu
# Convenience script to make generating multiple GSS's using the same
# set of parameters easier.  Generated files will have -# before the
# extension, and will be created in the current working directory.
# The generator letter (S|V) and generator arguments will be saved in
# a file called $prefix.genparam
#
# Environment:
#   CLASSPATH	must include everything the generators need to run
# Arguments: S|V num prefix generator_arguments
#   S|V:	generator to use: V=VertexGenerator, S=SegmentGenerator
#   num:	the number of files to generate
#   prefix:	the prefix to use for the batch generated filenames
#		files will be named "prefix-#".extension
#   generator_arguments: arguments for the generator, to be passed verbatim 

usage() {
    echo "Usage: $(basename $0) java-bin-path S|V num prefix generator_args"
    echo "	S|V     :   S = Segment Generator, V = VertexGenerator"
    echo "	num     :   number of GSS to generate"
    echo "	prefix  :   filename prefix to use"
    echo "	generator_arguments: omit filenames"
}

trap 'echo java execution exited with errors, aborting; exit 1' USR1

if [ $# -lt 5 ] ; then
    usage
    exit 1
fi

# decide which generator to use
generator_package=gss.generator
vertexg=VertexGenerator
segmentg=SegmentGenerator

gen="$1"
end="$2"
base="$3"

if [ "$gen" = V ] ; then
    generator_class=$generator_package.$vertexg
    generator=Vertex
else # assuming S
    generator_class=$generator_package.$segmentg
    generator=Segment
fi

# remove script arguments, leaving only generator arguments
shift 3

# save parameters
echo "$generator $@" > $base.genparam

log="$base.log"
[ -e "$log" ] && log="$base-$(date +%Y%m%dT%H%M%S).log"

for count in $(seq -w 1 $end ) ; do
    # check for currently running generator java processes
    countjava=$(pgrep -f -c "$generator_class")
    if [ 0"$countjava" -ge 2 ] ; then wait; fi

    basenum="$base-$count"
    echo Generating $(expr $count + 0) of $end >&2
    java $generator_class "$@" \
	"$basenum".gss "$basenum".matrix "$basenum".intersections \
	2>> "$log" || {
	    echo Generation of $(expr $count + 0) failed >&2 
	    kill -USR1 $$ 2>/dev/null
	} &
done 

exit 
